package com.malex.mxtracker.servlet;

import com.malex.mxtracker.action.ActionHandler;

import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import java.util.logging.Logger;

/**
 * @author Manusovich Alexander
 */
@SuppressWarnings("serial")
public class RestoreMailHandlerServlet extends HttpServlet {
    private static final Logger log = Logger.getLogger(ActionHandler.class.getName());

    public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);
        try {
            MimeMessage message = new MimeMessage(session, req.getInputStream());
            String request;
            Object content = message.getContent();
            if (content instanceof String) {
                request = (String) content;
            } else {
                Multipart multipart = (Multipart) content;
                request = (String) multipart.getBodyPart(0).getContent();
            }
            log.info("mail restore request " + request);
            System.out.println("request = " + request);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    private void answer(final MimeMessage message,
                        final String request,
                        final String sb) throws MessagingException, UnsupportedEncodingException {
        Properties properties = new Properties();
        Session mailsession = Session.getDefaultInstance(properties, null);
        javax.mail.Message msg = new MimeMessage(mailsession);
        msg.setFrom(new InternetAddress("manusovich.mobile@gmail.com", "mxTracker"));
        for (Address to : message.getFrom()) {
            msg.addRecipient(javax.mail.Message.RecipientType.TO, to);
        }
        msg.setSubject("mxTracker Response for <" + request + ">");
        msg.setText(sb);
        if (message.getFrom() != null && message.getFrom().length > 0) {
            log.info("send mail to " + message.getFrom()[0] + " body: " + sb);
        }
        Transport.send(msg);
    }

}